<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="/WEB-INF/shopizer-tags.tld" prefix="sm" %> 
<%@ page session="false" %>				
				
<script src="<c:url value="/resources/js/ckeditor/ckeditor.js" />"></script>
<script src="<c:url value="/resources/js/jquery.formatCurrency-1.4.0.js" />"></script>
<script src="<c:url value="/resources/js/jquery.alphanumeric.pack.js" />"></script>
<script src="<c:url value="/resources/js/json2.js" />"></script>
<script src="<c:url value="/resources/js/adminFunctions.js" />"></script>

<script src="<c:url value="/resources/js/jquery.showLoading.min.js" />"></script>
<script src="<c:url value="/resources/js/order-admin.js" />"></script>
<script src="<c:url value="/resources/js/common.js" />"></script>
<link href="<c:url value="/resources/css/showLoading.css" />" rel="stylesheet" />	
 
<link href="<c:url value="/resources/css/jqueryui/jquery-ui.css" />" rel="stylesheet" />
<script src="<c:url value="/resources/js/jqueryui/jquery.js" />" ></script>
<script src="<c:url value="/resources/js/jqueryui/jquery-ui.js" />" ></script>
<link href="<c:url value="/resources/css/order-admin.css" />" rel="stylesheet" />	
<script src="<c:url value="/resources/js/jquery.formatCurrency-1.4.0.js" />"></script>

<script>

$(document).ready(function(){
	$('#datePurchased').datepicker();
	$('#datePurchased').datepicker("option", "dateFormat", "dd-mm-yy");
	$('#datePurchased').datepicker( "setDate", new Date());
	
	$('#productDateAvailable').datepicker();
	$('#productDateAvailable').datepicker("option", "dateFormat", "dd-mm-yy");
	$('#productDateAvailable').datepicker( "setDate", new Date());
	
	addProductHandler();

	$("#addProdImportName").autocomplete({
	    width: 300,
	    max: 10,
	    delay: 100,
	    minLength: 1,
	    autoFocus: true,
	    cacheLength: 2,
	    scroll: true,
	    highlight: false,
	    source: function(request, response) {
	        $.ajax({
	            url: '<c:url value="/admin/orders/import/productImportInfo.html"/>',
	            responseType:"application/json;charset=utf-8",
	            contentType:"application/json;charset=utf-8",
	            dataType: "json",
	            data: { term: request.term },
	            success: function( data, textStatus, jqXHR) {
	            	if(data.length)
	                console.log( data);
	                var result = data.response.data;
	                response( $.map( result, function( item ) {
	                    return {
	                        label: item.desc,
	                        value: item.desc,
	                        price: item.price
	                    }
	                }));
	            },
	            error: function(jqXHR, textStatus, errorThrown){
	                 console.log( textStatus);
	            }
	        });
	    },
	    select: function( event, ui ) {
	        $('#showPrice').val(ui.item.price);
	        $('#showPrice').formatCurrency({ colorize: true, negativeFormat: '-%s%n', roundToDecimalPlace: -1, eventOnDecimalsEntered: true, symbol: ''});
	    },

	});

	$("#saveManufacture").click(function(){
		var hasError = false;
		$("#newManufacturePanel").find('.highlight').each(function(){
			if($(this).val().length <1){
				$("#manufactureMessage").html('<s:message code="NotEmpty.product.info" text="Please enter yellow field"/>');
				$("#manufactureMessage").css("color","red");
				hasError = true;
				return;
			}
		});
		
		if(hasError == true)
			return;
		var data = {
	    		"manufactureName" : $("#manufactureName").val(),
	    		"manufactureTitle" : $("#manufactureTitle	").val()
	    };
		$.ajax({
			  type: 'POST',
			  dataType: "json",
			  responseType:"application/json;charset=utf-8",
	          contentType:"application/json;charset=utf-8",
			  url: '<c:url value="/admin/catalogue/manufacturer/saveShort.html"/>',
		  	  contentType: 'application/json',
	          data: JSON.stringify(data),
			  success: function(response){
				  	var status = response.response.status;
				  	var data = response.response.data;
				  	console.log(data);
					var manufacture = data;
					if(status==0 || status ==9999) {
						var name = manufacture[0].manName;
						$("#manufactureMessage").html('<s:message code="label.order.manufacture.create.success" text="Success create product" />: ' + name);
						$("#manufactureMessage").css("color","green");
						resetField($("#newManufacturePanel"));
					} else {
						$("#manufactureMessage").html('<s:message code="label.order.manufacture.create.error" text="Error create product" />: </br>' + manufacture[0].errorMessage);
						$("#manufactureMessage").css("color","red");
					}
				}
			});
	});
	
	$("#saveCategory").click(function(){
		var hasError = false;
		$("#newCategoryPanel").find('.highlight').each(function(){
			if($(this).val().length <1){
				$("#categoryMessage").html('<s:message code="NotEmpty.product.info" text="Please enter yellow field"/>');
				$("#categoryMessage").css("color","red");
				hasError = true;
				return;
			}
		});
		
		if(hasError == true)
			return;
		var data = {
	    		"categoryParentId" : $("#categoryParentId").val(),
	    		"categoryCode" : $("#categoryCode").val(),
	    		"categoryName" : $("#categoryName").val(),
	    		"cateVisible" : $("#cateVisible").val()
	    };
		$.ajax({
			  type: 'POST',
			  dataType: "json",
			  responseType:"application/json;charset=utf-8",
	          contentType:"application/json;charset=utf-8",
			  url: '<c:url value="/admin/categories/saveShort.html"/>',
		  	  contentType: 'application/json',
	          data: JSON.stringify(data),
			  success: function(response){
				  	var status = response.response.status;
				  	var data = response.response.data;
				  	console.log(data);
					var category = data;
					if(status==0 || status ==9999) {
						var name = category[0].cateName;
						var code = category[0].cateCode;
						$("#categoryMessage").html('<s:message code="label.order.category.create.success" text="Success create product" />: ' + name + ' - ' + code);
						$("#categoryMessage").css("color","green");
						resetField($("#newCategoryPanel"));
					} else {
						$("#categoryMessage").html('<s:message code="label.order.category.create.error" text="Error create product" />: </br>' + category[0].errorMessage);
						$("#categoryMessage").css("color","red");
					}
				}
			});
	});

	$("#saveProduct").click(function(){
		var hasError = false;
		$("#newProductPanel").find('.highlight').each(function(){
			if($(this).val().length <1){
				$("#productMessage").html('<s:message code="NotEmpty.product.info" text="Please enter yellow field"/>');
				$("#productMessage").css("color","red");
				hasError = true;
				return;
			}
		});
		
		if(hasError == true)
			return;
		
		var data = {
	    		"sku" : $("#sku").val(),
	    		"productName" : $("#productName").val(),
	    		"productImportPriceAmount" : $("#productPriceImportAmount").val(),
	    		"productManuId" : $("#productManuId").val(),
	    		"productDateAvailable" : $("#productDateAvailable").val(),
	    		"quantity" : $("#quantity").val(),
	    		"productPriceAmount" : $("#productPriceAmount").val()
	    };
		$.ajax({
			  type: 'POST',
			  dataType: "json",
			  responseType:"application/json;charset=utf-8",
	          contentType:"application/json;charset=utf-8",
			  url: '<c:url value="/admin/products/saveShort.html"/>',
		  	  contentType: 'application/json',
	          data: JSON.stringify(data),
			  success: function(response){
				  	var status = response.response.status;
				  	var data = response.response.data;
				  	console.log(data);
					var product = data;
					if(status==0 || status ==9999) {
						var name = product[0].productName;
						var sku = product[0].productSku;
						$("#productMessage").html('<s:message code="label.order.product.create.success" text="Success create product" />: ' + name + ' - ' + sku);
						$("#productMessage").css("color","green");
						resetField($("#newProductPanel"));
					} else {
						$("#productMessage").html('<s:message code="label.order.product.create.error" text="Error create product" />: </br>' + product[0].errorMessage);
						$("#productMessage").css("color","red");
					}
				}
			});
	});

	
	$("#checkPhone").click(function() {
		$('#transactionList').empty();
		resetMessages();
		$("#waiting").css("display","block");
		loadCustomerByPhone();
	});
	
	$("#sendInvoiceAction").click(function() {
		resetMessages();
		$('.sm').showLoading();
		sendInvoice('<c:out value="${order.order.id}"/>');
	});
	
	$(".close-modal").click(function() {

	}); 
		
}); 


    $(function() {
        $("#refund").submit(function() {
        	$('#refundButton').addClass('disabled');
 			$('#refundModal').showLoading();
            
            $.ajax({
                'type': 'POST',
                'url': "<c:url value="/admin/orders/refundOrder.html"/>",
                responseType:"application/json;charset=utf-8",
	            contentType:"application/json;charset=utf-8",
                'data': JSON.stringify(data),
                'dataType': 'json',
                'success': function(result) {
                   $('#refundModal').hideLoading();
                   var response = result.response;
                   var status = response.status;
                   if(status==0 || status ==9999) {
                	    //window.location='<c:url value="/admin/orders/editOrder.html" />?id=<c:out value="${order.order.id}" />';
                        $(".alert-success-modal").show();
                        //$(".close-modal").show();
                   } else { 
                        $(".alert-error-modal").html(response.statusMessage);
                        $(".alert-error-modal").show();
                   }
                   $('#refundButton').removeClass('disabled');
                }
            });
 
            return false;
        });
    });
 

</script>

<div class="tabbable">

<jsp:include page="/common/adminTabs.jsp" />
<div class="tab-content">
<div class="tab-pane active" id="order-section">

	<div class="sm-ui-component" id="order-main-component">
		<p class="p-title">
			<h3><s:message code="label.order.import" text="Create import order" /></h3>
		</p>
			
     	<c:url var="importOrderSave" value="/admin/orders/import/saveNew.html"/>
        <form:form method="POST" enctype="multipart/form-data" commandName="order" action="${importOrderSave}">
	   		<form:errors path="*" cssClass="alert alert-error" element="div" />
            <div id="store.success" class="alert alert-success" style="<c:choose><c:when test="${success!=null}">display:block;</c:when><c:otherwise>display:none;</c:otherwise></c:choose>">
            	<s:message code="message.success" text="Request successfull"/></div>   
            <div id="store.error" class="alert alert-error" style="display:none;">
            	<s:message code="message.error" text="An error occured"/></div>
			<form:hidden path="order.billing.firstName"/>
			<form:hidden path="order.billing.lastName"/>
			<form:hidden path="order.delivery.firstName"/>
 		<div class="span8">
        	<div class="span4" style="margin-left:0px;">
        	    <label><s:message code="label.order.paymentmode" text="Payment mode"/></label></br>
              	<div class="controls">      
		 			 <form:select path="order.paymentType" cssClass="order-dropdown">
		 			 	<form:option value="MONEYORDER">
							<s:message code="label.order.paymentmode.moneyorder" text="Money Order"/>
						</form:option>
		 			 	<form:option value="LOAN">
		 			 		<s:message code="label.order.paymentmode.loan" text="Loan"/>
		 			 	</form:option>
		 			 </form:select>
               </div>
        	</div>
        	<div class="span4" style="margin-left:0px;">
              	<s:message code="label.customer.order.date" text="Order date"/></br>			 		
              	<div class="controls">      
					<form:input cssClass="input-large" path="datePurchased" class="small" type="text"/>
			 		<span class="help-inline"><form:errors path="datePurchased" cssClass="error" /></span>      
               </div>
        	</div>
        </div>
		<br />				
        <div class="span8">
        	<div class="span4" style="margin-left:0px;">
           		<label><s:message code="label.entity.order.status" text="Order Status"/></label>	 
              	<div class="controls">      
              		<form:select path="order.status" cssClass="order-dropdown">
           				<c:forEach items="${orderStatusList}" var="orderStatus">
           					<form:option value="${orderStatus}">
           						<s:message code="label.entity.order.status.${orderStatus}" text="${orderStatus}"/>
           					</form:option>
           				</c:forEach>						
    				</form:select>      
               </div>
        	</div>
        	<div class="span4" style="margin-left:0px;">
           		<label><s:message code="label.payment.status" text="Payment Status"/></label>	 
              	<div class="controls">      
              		<form:select path="order.paymentStatus" cssClass="order-dropdown">
           				<c:forEach items="${paymentStatusList}" var="paymentStatus">
           					<form:option value="${paymentStatus}">
           						<s:message code="label.payment.status.${paymentStatus.value}" text="${paymentStatus.value}"/>
           					</form:option>
           				</c:forEach>						
    				</form:select>      
               </div>
        	</div>
        </div>
	
      
      	 <div class="span8" style="margin-top:20px;">
		      <table class="table table-bordered table-striped"> 
					<thead> 
						<tr> 
							<th colspan="2" width="47%"><s:message code="label.order.product.title" text="Item"/></th> 
							<th colspan="1" width="13%"><s:message code="label.quantity" text="Quantity"/></th> 
							<th width="13%"><s:message code="label.order.price" text="Price"/></th>
							<th width="17%"><s:message code="label.order.subtotal" text="Total"/></th>
							<th width="10%"><s:message code="label.order.action" text="Action"/></th>  
						</tr> 
					</thead> 
					
 				    <tbody id="productsList">
 				    	
						<tr class="totalClass" id="subtotalTd" > 
							<td colspan="3">&nbsp;</td> 
							<td><strong><s:message code="label.order.subtotal" text="Sub-total"/></strong></td> 
							<td colspan="2" id="subtotal"></td> 
						</tr>
						<tr class="totalClass" >
							<td colspan="3">&nbsp;</td> 
							<td ><strong><s:message code="label.order.total" text="Total"/></strong></td>
							<td colspan="2" id="total"></td>
						</tr> 
					</tbody>
				</table>
    	  </div>
		<br/>   
 		
 		<div class="span8"> 				
			<div style="margin-bottom: 20px;">
				<s:message code="label.order.product.title" text="Product" />: 
				<input type="text" name="productName" id="addProdImportName"/> &nbsp;&nbsp;&nbsp;
				<s:message code="label.order.product.quantity" text="Quantity" />: 
				<input type="text" name="quantity" id="addQuantity" value="1" style="width:25px;"/> &nbsp;&nbsp;&nbsp;
				<s:message code="label.order.product.price" text="Price" />: 
				<input type="text" name="price" id="showPrice" style="width:100px;"/> &nbsp;&nbsp;&nbsp;
				<input type="button" value="<s:message code='label.generic.add' />" id="addProductImport"><br>
				<span id="addingError" style="color:red;"></span>
			</div>
		</div>
		
		<s:message code="label.category.root" text="Root" var="rootVar"/>			
		
		<div class="span8">
			<div id="accordion">
			  <h4><s:message code="label.order.product.new.title" text="New product"/></h4>
			  <div id="newProductPanel">
				<div class="span7">
				<div class="productMessage" id="productMessage"></div>
			  	<div class="span4" style="margin-left:0px;">
				  	<div class="control-group">
                      <label class="required"><s:message code="label.product.sku" text="Sku"/> - <s:message code="label.generic.alphanumeric" text="Alphanumeric" /></label>
                      <div class="controls">
                      	<input type="text" class="input-large highlight" id="sku" name="sku"/>
                      </div>
               		</div>
               		
               		<div class="control-group">
                           <label class="required"><s:message code="label.productedit.productname" text="Product name"/></label>
                           <div class="controls">
                           	<input type="text" id="productName" name="productName" class="input-large highlight" />
                           </div>
                      </div>
                      
                      <div class="control-group">
						<label class="required"><s:message code="label.product.import.price" text="Price"/></label>
                       	<div class="controls">
                               <input id="productPriceImportAmount" name="productPriceImportAmount" class="highlight" type="text"/>
                       	</div>
                 		</div>
                 		
                 		<div class="control-group">
                       	<label><s:message code="label.product.manufacturer" text="Manufacturer"/></label>
                         	<div class="controls">                          	
                         		<select id="productManuId" name="productManuId" class="order-dropdown highlight">
                          		<option value="-1">-<s:message code="label.order.select" text="Select"/>-</option>
		           				<c:forEach items="${manufacturers}" var="manufacturer">
									<option value="${manufacturer.id}">
										<c:out value="${manufacturer.descriptions.toArray()[0].name}" />
									</option>
		           				</c:forEach>						
                         		</select>
                         	</div>
                   	</div>
                   	
              		</div>
              		
              		<div class="span3" style="margin-left:0px;">
				  	<div class="control-group">
                      	<label><s:message code="label.product.availabledate" text="Date available"/></label>
                        <div class="controls">
                       		 <input id="productDateAvailable" name="productDateAvailable" class="small highlight" type="text" /> 
                        </div>
               		</div>
               		
                 		<div class="control-group">
                       	<label class="required"><s:message code="label.productedit.qtyavailable" text="Quantity available"/></label>
                       	<div class="controls">
                               <input type="text" id="quantity" name="quantity" class="highlight"/>
                       	</div>
                 		</div>
                 		
                   	<div class="control-group">
						<label class="required"><s:message code="label.product.sale.price" text="Price"/></label>
                       	<div class="controls">
                               <input id="productPriceAmount" name="productPriceAmount" class="highlight" type="text"/>
                       	</div>
                 		</div>
                 		
                 		<div class="control-group" style="visibility:hidden">
                       		<label><s:message code="label.product.category" text="Category"/></label>
                         	<div class="controls">
                         		<select id="productCategoryId" name="productCategoryId" class="order-dropdown">
                          		<option value="-1">${rootVar}</option>
		           				<c:forEach items="${categories}" var="category">
									<option value="${category.id}">
										<c:out value="${category.descriptions.toArray()[0].name}" />
									</option>
		           				</c:forEach>
                         		</select>
                         	</div>
                   		</div>
                   	
                   	<div class="control-group">
                       	<input type="button" class="btn btn-medium btn-primary" value="Save" id="saveProduct"></input>
                   	</div>      
              		</div>
				
				</div>					
			  </div>
			  <h4><s:message code="label.order.category.new.title"  text="New category"/></h4>
			  <div id="newCategoryPanel">
			  	<div class="span7">
			  		<div class="productMessage" id="categoryMessage"></div>
			  		<div class="span4" style="margin-left:0px;">
			  			<div class="control-group">
	                        <label><s:message code="label.category.parentcategory" text="Category parent"/></label>
	                        <div class="controls">
                        		<select id="categoryParentId" class="order-dropdown">
                        			<option value="-1" label="${rootVar}" />
				  					<c:forEach items="${categories}" var="category">
										<option value="${category.id}">
											<c:out value="${category.descriptions.toArray()[0].name}" />
										</option>
		           					</c:forEach>
			       				</select>
	                        </div>
	                  	</div>
	                  	
	                  	<div class="control-group">
	                        <label><s:message code="label.category.code" text="Category code"/></label>
		                        <div class="controls">
		                        	<input type="text" class="input-large highlight" id="categoryCode"/>
		                        </div>
	                 	</div>
			  		</div>
			  		
			  		<div class="span3" style="margin-left:0px;">
			  			<div class="control-group">
	                        <label><s:message code="label.entity.visible" text="Visible"/></label>
	                        <div class="controls" style="height: 28px;">
	                        	<input type="checkbox" id="cateVisible" checked="checked"/>
	                        </div>
	                  	</div>
	                  	
	                  	<div class="control-group">
							<label><s:message code="label.productedit.categoryname" text="Category name"/></label>
	                        <div class="controls">
	                        	<input class="input-large highlight" id="categoryName" type="text" />
	                        </div>
	                 	</div>
	                  	
	                  	<div class="control-group">
                       		<input type="button" class="btn btn-medium btn-primary" value="Save" id="saveCategory"></input>
                   		</div>
			  		</div>
			  	</div>
			  </div>
			  <h4><s:message code="label.order.manufacture.new.title"  text="New manufacture"/></h4>
			  <div id="newManufacturePanel">
			  	<div class="span7">
			  		<div class="productMessage" id="manufactureMessage"></div>
			  		<div class="span4" style="margin-left:0px;">
			  			<div class="control-group">
	                        <label class="required"><s:message code="label.manufactureredit.manufacturername" text="Manufacturer Name"/></label>
	                        <div class="controls">
	                        	<input type="text" class="input-large highlight" id="manufactureName"/>
	                        </div>
	            		</div>
	            	</div>
	            	
	            	<div class="span3" style="margin-left:0px;">
			  			<div class="control-group">
			  				<div class="control-group">
		                        <label><s:message code="label.manufactureredit.manufacturertitle" text="Manufacturer Title"/></label>
		                        <div class="controls">
		                        	<input type="text" class="input-large" id="manufactureTitle"/>
		                        </div>
		                  	</div>
	            		</div>
	            		
	            		<div class="control-group">
                       		<input type="button" class="btn btn-medium btn-primary" value="Save" id="saveManufacture"></input>
                   		</div>
	            	</div>         	
	            </div>	  	
			  </div>
			</div>
							
		</div>
		<script type="text/javascript">
			$( "#accordion" ).accordion({
				header: "h4", collapsible: true, active: false, heightStyle: "content"
		    });
		</script>
		
		</br>     					
        <div class="span8"> 
 		   <div class="control-group">  
                <label><s:message code="label.generic.comments" text="Comment"/></label>
                 <div class="controls">
                     <form:textarea  cols="15" rows="3" path="orderHistoryComment"/>
                </div> 
           </div>
         
          <div class="form-actions">
          		<button  type="submit" class="btn btn-medium btn-primary" >
          			<s:message code="button.label.create" text="Save Order"/></button>
  		  </div>
 		</div> 
		
		<br/>   
   		</form:form>       
      </div>
	 </div>
  </div>

<div id="customersModal"  class="modal hide" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="width:900px;z-index:500000;">
  <div class="modal-header">
          <button type="button" class="close close-modal" data-dismiss="modal" aria-hidden="true">X</button>
          <h3 id="myModalLabel"><s:message code="label.order.customers" text="List of customers" /></h3>
  </div>
    <div class="modal-body">
           <p>
			<table class="table table-hover" style="font-size:10px;">
			<thead>
				<tr>
				<th><s:message code="label.entity.firstName" text="First name" /></th>
				<th><s:message code="label.entity.lastName" text="Last name" /></th>
				<th><s:message code="label.entity.email" text="Email" /></th>
				<th><s:message code="label.entity.phone" text="Phone number" /></th>
				<th><s:message code="label.entity.bilingAddr" text="Billing address" /></th>
				<th><s:message code="label.entity.shippingAddr" text="Shipping address" /></th>
				</tr>
			</thead>
			<tbody id="transactionList">
			</tbody>
			</table>
           </p>
             
    </div>  
    <div class="modal-footer">
           <button class="btn btn-primary" id="closeModal" data-dismiss="modal" aria-hidden="true"><s:message code="button.label.close" text="Close" /></button>
    </div>
</div>
